package com.sk.bilibili.service;

import com.sk.bilibili.bean.Member;
import com.sk.bilibili.dto.QrCode;
import com.sk.bilibili.other.R;
import com.sk.bilibili.property.QrProperty;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QrCodeUtils;
import com.sk.bilibili.utils.RedisUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author 邵康
 * @date 2021/11/23 13:30
 */
@Service
public class QrCodeService {

    @Autowired
    private QrProperty qrProperty;
    @Autowired
    private QrCodeUtils qrCodeUtils;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private MemberService memberService;

    public R<QrCode> qrCode() {
        QrCode qrCode = qrCodeUtils.generateQrCode();
        redisUtils.set(qrCode.getCode(), "", qrProperty.getLostTime(), TimeUnit.MINUTES);
        return R.success(qrCode);
    }

    public R<Member> check(String code) {
        String id = redisUtils.get(code);
        if (id == null) return R.error("二维码已经失效", 501);
        if (id.equals("")) return R.error();
        redisUtils.delete(code);
        Member member = memberService.getById(Integer.parseInt(id));
        BSessionUtils.setMemberId(member.getId());
        return R.success(member);
    }

    @SneakyThrows
    public void generate(String info, HttpServletResponse response) {
        qrCodeUtils.generate(info, response.getOutputStream());
    }

    public R<Void> scan(String code) {
        if (!redisUtils.contains(code)) return R.error("验证码失效", 501);
        int memberId = BSessionUtils.getMemberId();
        redisUtils.set(code, String.valueOf(memberId));
        return R.success();
    }

}
